package com.luobd.base.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.luobd.base.*;
import com.luobd.base.service.IAuthService;
import com.luobd.base.util.JWTUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


@Service
public class DefaultAuthService implements IAuthService {

    private static final String DEFAULT_USER = "admin";


    private static final String DEFAULT_PASSWORD = "admin";


    @Resource
    private JWTUtil jwtUtil;


    private static final Map<Long,String> TOKEN_CACHE = Maps.newConcurrentMap();


    private static final List<Role> DEFAULT_ROLES = Lists.newArrayList(Role.of(-1L,"admin","admin"));


    @Override
    public ResponseData<String> auth(String username, String password) {
        if(!DEFAULT_USER.equals(username) || !DEFAULT_PASSWORD.equals(password)) {
            return ResponseData.error("用户或密码不正确");
        }
        CurrentUserInfo userInfo = new CurrentUserInfo();
        userInfo.setUsername(username);
        userInfo.setTrueName(DEFAULT_USER);
        userInfo.setRoles(DEFAULT_ROLES);
        userInfo.setUserInfoId(-1L);
        userInfo.setAccountId(-1L);
        String token = jwtUtil.createToken(userInfo);
        cacheToken(-1L,token);
        return ResponseData.success(token);
    }

    @Override
    public ResponseData<Boolean> logout() {
        CurrentUserInfo info = CurrentRequestHolder.get();
        if(info != null) {
            TOKEN_CACHE.remove(info.getUserInfoId());
        }
        return ResponseData.success(Boolean.TRUE);
    }

    @Override
    public String getCacheTokenByUserId(Long userId) {
        return TOKEN_CACHE.get(userId);
    }

    @Override
    public ResponseData<Base64Captcha> getCaptchaBase64() {
        Base64Captcha captcha = Base64Captcha.of();
        return ResponseData.success(captcha);
    }

    @Override
    public boolean checkCaptcha(String id, String captcha) {
        return true;
    }

    private void cacheToken(Long userId,String token) {
        TOKEN_CACHE.put(userId,token);
    }

    private void removeCache(Long userId) {
        TOKEN_CACHE.remove(userId);
    }
}
